package com.tensquare.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.handler.HandlerResolver;

/**
 * Created by WF on 2019/9/25 9:49
 * 网关过滤器
 */
@Component
public class MyZuulFilter extends ZuulFilter {
    //1.代表过滤器执行的时机，可取值：pre/post/error/route,具体参见讲义
    @Override
    public String filterType() {
        return "pre";
    }
    //2.代表过滤器执行顺序，值越小，越先执行
    @Override
    public int filterOrder() {
        return 0;
    }
    //3.代表是否执行此过滤器,true:代表执行，false：不执行
    @Override
    public boolean shouldFilter() {
        return true;
    }
    //4.执行过滤器的业务逻辑，只要返回的是对象，都会向下执行，即便是null也不例外
    //业务：就是将我们jwt签权所用到的请求头向下传递
    @Override
    public Object run() throws ZuulException {
        //4.1)得到当前请求的上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //4.2)得到请求对象
        HttpServletRequest request = currentContext.getRequest();
        //4.3)得到jwt用到的请求头
        String header = request.getHeader("Authorization");
        //4.4)判断是否有内容
        if(StringUtils.isNotBlank(header)){ //如果不为null，就向下传递
            currentContext.addZuulRequestHeader("Authorization",header);
        }
        return null;
    }
}
